package com.module.prms.manager;

import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;

import base.dao.GenericHibernateDao;
import base.manager.GenericHibernateManager;
import base.util.Page;
import base.util.ResolveUnit;

import com.module.prms.ReqBaseBean;
import com.module.prms.dao.MenuDao;
import com.module.prms.dao.RoleDao;
import com.module.prms.dao.RoleOperationDao;
import com.module.prms.dao.RoleOrgDao;
import com.module.prms.dao.UserDao;
import com.module.prms.dao.UserOrgDao;
import com.module.prms.dao.UserRoleDao;
import com.module.prms.vo.FMenuTree;
import com.module.prms.vo.PrmsMenu;
import com.module.prms.vo.PrmsRole;
import com.module.prms.vo.PrmsRoleOperation;
import com.module.prms.vo.PrmsRoleOrg;
import com.module.prms.vo.PrmsUser;
import com.module.prms.vo.PrmsUserOrg;
import com.module.prms.vo.PrmsUserRole;



public class UserManager extends GenericHibernateManager<PrmsUser, String>{
	private UserManager() {
	}
	
	private static UserManager manager;

	public synchronized static UserManager getInstance() {
		if (manager == null)
			manager = new UserManager();
		return manager;
	}
	static Logger logger = Logger.getLogger(UserManager.class.getName());
	
	UserDao dao = UserDao.getInstance();
	UserOrgDao uorgdao = UserOrgDao.getInstance();
	RoleOrgDao rodao = RoleOrgDao.getInstance();
	RoleDao roledao = RoleDao.getInstance();
	UserRoleDao urd = UserRoleDao.getInstance();
	RoleOperationDao roptdao = RoleOperationDao.getInstance();
	MenuDao mdao = MenuDao.getInstance();
	
	
	/**
	 * <保存-修改> <将用户信息保存（修改）到数据库>
	 * 
	 * @param bean
	 * @throws Exception
	 * @see [类、类#方法、类#成员]
	 */
	
	public boolean add(PrmsUser pu) throws Exception {
		System.err.println("===========本地新增==========");
		Session session = this.getSession();
		Transaction tx = null;
		tx = session.beginTransaction();
		String id = null;
		boolean isTrue = false;
		id = pu.getCuserId();
		try {
			isTrue = dao.saveOrUpdate(session, pu);
			if (!(id == null) && isTrue)// edit 2011.10.26
			{
				StringBuffer sb = new StringBuffer();
				sb.append("delete from PrmsUserOrg as obj where obj.cuserId='"
						+ id + "'");
				isTrue = uorgdao.deleteByQuery(session, sb.toString());
			}
			List<PrmsUserOrg> userorglist = new ArrayList();
			userorglist = pu.getOrgs();
			PrmsUserOrg puo = new PrmsUserOrg();
			if (!(userorglist == null) && isTrue)// edit 2011.10.26
			{
				for (int i = 0; i < userorglist.size(); i++) {
					puo = (PrmsUserOrg) ResolveUnit.resolve(
							ResolveUnit.getJsonStr(userorglist.get(i)),
							PrmsUserOrg.class);
					puo.setCuserId(pu.getCuserId());
					isTrue = uorgdao.save(session, puo);
				}
			}
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			throw e;
		} finally {
			this.closeSession();
		}
		return isTrue;
	}
    
	/**
	 * <删除> <将用户信息从数据库删除>
	 * 
	 * @param bean
	 * @see [类、类#方法、类#成员]
	 */
	public void del(PrmsUser obj) throws Exception{
		this.delete(obj);
	}

	public boolean remove(List<String> idArray)throws Exception{
		System.out.println("====本地方法删除===");
		Session session = this.getSession();
		Transaction tx = null;
		tx = session.beginTransaction();
		StringBuffer sb = new StringBuffer();
		boolean isTrue = false;
		try {
			for(String s:idArray){
				sb.append("delete from PrmsUserOrg as obj where obj.cuserId='"
						+ s + "'");
				isTrue = uorgdao.deleteByQuery(session, sb.toString());
				if (isTrue)
					isTrue = dao.deleteByKey(session, s);
			}
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			throw e;
		}finally {
			this.closeSession();
		}
		return isTrue;
	}
	
	/**
	 * <修改> <修改数据库中的用户信息>
	 * 
	 * @param bean
	 * @see [类、类#方法、类#成员]
	 */
	public void upd(PrmsUser obj) throws Exception{
		this.update(obj);
	}

	/**
	 * <列表> <列表显示数据库用户信息>
	 * 
	 * @param bean
	 * @see [类、类#方法、类#成员]
	 */
	public Page list(Page pageObj,PrmsUser pu) throws Exception{
		Session session = this.getSession();
		Page page = new Page();
		try {
			page = dao.getList(session,pu, pageObj.getStart(),pageObj.getLimit());
		} catch (Exception e) {
			throw e;
		} finally {
			this.closeSession();
		}
		return page;
	}

	/**
	 * <根据id查找数据> <列表显示数据库用户信息>
	 * 
	 * @param bean
	 * @see [类、类#方法、类#成员]
	 */
	public PrmsUser findebyid(PrmsUser prmsUser) throws Exception{
		Session session = this.getSession();
		PrmsUser pu = null;
		try {
			pu = dao.get(session,prmsUser.getCuserId());
			pu.setOrgs(uorgdao.getList(session,pu.getCuserId()));
		} catch (Exception e) {
			throw e;
		} finally {
			this.closeSession();
		}
		return pu;
	}

	/**
	 * 根据用户名查找
	 * 
	 * @param bean
	 */
	public PrmsUser findUserbyName(PrmsUser pu)throws Exception {
		//PrmsUser prmsUser = (PrmsUser)this.getUniqueByProperty("cuserName", pu.getCuserName());
		Session session = this.getSession();
		PrmsUser prmsUser = dao.findUserbyName(session, pu.getCuserName());
		return prmsUser;
	}

	/**
	 * 查找组织下的角色信息
	 * 
	 * @param bean
	 * @see [类、类#方法、类#成员]
	 */
	public List getorgrole(String orgid) throws Exception{
		Session session = this.getSession();
		List rolelist = new ArrayList();
		List<PrmsRole> orgrolelist = null;
		try {
			orgrolelist = roledao.getorgrole(session,orgid);
			logger.info("orgrolelist.size=" + orgrolelist.size());
			for (PrmsRole pro : orgrolelist) {
				PrmsRole pr = roledao.get(session,pro.getCroleId());
				if (pr.getCroleStatus().equals("1")) {
					rolelist.add(pr);
				}
			}
		} catch (Exception e) {
			throw e;
		} finally {
			this.closeSession();
		}
		return rolelist;

	}

	public List getorg_role(PrmsRoleOrg pro) throws Exception{
		logger.info("orgid=" + pro.getCorgId());
		List list = new ArrayList();
		if(!"".equals(pro.getCorgId())){
			list=this.getorgrole(pro.getCorgId());
		}
		return list;
	}

	/**
	 * 保存与用户并联的角色
	 * 
	 * @param bean
	 * @see [类、类#方法、类#成员]
	 */
	public boolean  saveUserRole(String userid,List<String> list) throws Exception{
		Session session = this.getSession();
		Transaction tx = null;
		tx = session.beginTransaction();
		boolean isTrue = false;
		StringBuffer sb = new StringBuffer();
		sb.append("delete from PrmsUserRole as obj where obj.cuserId='"
				+ userid + "'");
		try {
			urd.deleteByQuery(session,sb.toString());
			if(list.size()<=0){
				isTrue = true ;
			}else{
				for (String roleid : list) {
					PrmsUserRole pur = new PrmsUserRole();
					pur.setCuserId(userid);
					pur.setCroleId(roleid);
					pur.setDcreateTime(new Date());
					isTrue = urd.save(session,pur);
				}
			}

			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			throw e;
		} finally {
			this.closeSession();
		}
		return isTrue;
		
	}

	/**
	 * 获取与用户并联的角色
	 * 
	 * @param bean
	 * @see [类、类#方法、类#成员]
	 */
	public List getUserRole(String userid) throws Exception{
		Session session = this.getSession();
		List rolelist = new ArrayList();
		List<PrmsUserRole> userRolelist = null;
		try {
			userRolelist = urd.getUserRole(session,userid);
			for (PrmsUserRole pur : userRolelist) {
				rolelist.add(roledao.get(session,pur.getCroleId()));
			}
		} catch (Exception e) {
			throw e;
		} finally {
			this.closeSession();
		}
		return rolelist;
	}

	
	public void getPrmsUserRole(ReqBaseBean bean) throws Exception{
		Session session = this.getSession();
		Map map = bean.getResult();
		String userid = (String) map.get("userid");
		List<PrmsUserRole> userRolelist = null;
		try {
			userRolelist = urd.getUserRole(session,userid);
		} catch (Exception e) {
			throw e;
		} finally {
			this.closeSession();
		}
		map.clear();
		map.put("userRoleList", userRolelist);
		bean.setResult(map);
	}
	
	/**
	 * 修改密码
	 * 
	 * @param bean
	 */
	public boolean changePassword(PrmsUser prmsUser) throws Exception{
		Session session = this.getSession();
		Transaction tx = null;
		tx = session.beginTransaction();
		String userName = prmsUser.getCuserName();
		String newPwd = prmsUser.getCuserPwd();
		List<PrmsUser> users = null;
		PrmsUser userInfo = null;
		String hql = "from PrmsUser as obj where obj.cuserName='" + userName+ "'";
		boolean flag=false;;
		try {
			users = dao.findBySQL(session,hql);
			// 相同userName记录只可能存在一条
			if (users.size() > 0)
				userInfo = users.get(0);
			
			userInfo.setCuserPwd(newPwd);
			flag=dao.update(session, prmsUser);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			throw e;
		} finally {
			this.closeSession();
		}
		return flag;
	}

	/**
	 * 获取用户登录权限信息
	 */
	public PrmsUser getUserInfo(PrmsUser prmsUser) throws Exception{
		Session session = this.getSession();
		Transaction tx = null;
		tx = session.beginTransaction();
		PrmsUser pu = new PrmsUser();
		String hql = "from PrmsUser as obj where obj.cuserName='" + prmsUser.getCuserName()+ "'";
		try {
			List<PrmsUser> ul = dao.findBySQL(session,hql);
			if (ul != null && ul.size() > 0) {
				for (PrmsUser put : ul) {
					if (put.getCuserPwd().equals(prmsUser.getCuserPwd())
							&& put.getCuserStatus().equals("1")) {
						pu = put;
					}
				}
			}
			String uorghql = "from PrmsUserOrg as obj where obj.cuserId='"
					+ pu.getCuserId() + "'";
			List<PrmsUserOrg> puol = uorgdao.findBySQL(session,uorghql);
			List<PrmsRole> rolel = null;
			if (puol != null && puol.size() > 0) {
				List<PrmsUserOrg> puolt = new ArrayList();
				for (PrmsUserOrg puo : puol) {
					String uorgrolehql = "select pr from PrmsRole pr where pr.orgid='"
							+ puo.getCorgId()
							+ "' and  pr.croleStatus='1' and "
							+ "pr.croleId in (select pur.croleId from PrmsUserRole pur where pur.cuserId ='"
							+ pu.getCuserId() + "')";
					rolel = roledao.findBySQL(session,uorgrolehql);
					if (rolel != null && rolel.size() > 0) {
						puo.setRolelist(rolel);
					}
					puolt.add(puo);
				}
				pu.setOrgs(puolt);
			}
			//bean.setPrmsuser(pu);
			
			if (rolel != null && rolel.size() > 0) {
				pu.setCfirstLogin("1 ");
				dao.update(session,pu);
			}
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			throw e;
		} finally {
			this.closeSession();
		}
		return pu;
	}

	/**
	 * 一、先获取角色的操作信息。 二、通过操作信息取出菜单信息
	 * 
	 * */
	public Map getUserMenu(String roleid) throws Exception{
		Session session = this.getSession();
		//add
		Map map = new HashMap();
		//end
		FMenuTree fmt = new FMenuTree();
		List<PrmsMenu> UMenu = null;
		try {
			fmt = roptdao.getroleopt(session,roleid);
			List<PrmsRoleOperation> optlist = fmt.getTree();
			StringBuffer menuids = new StringBuffer();
			int i = 0;
			Set<String> set = new HashSet<String>();
			for (PrmsRoleOperation pm : optlist) {
				set.add(pm.getCmenuId());
			}
			for (Iterator<String> it = set.iterator(); it.hasNext();) {
				String str = (String) it.next();
				menuids.append("'" + str + "',");
			}
			String mids = menuids.toString();
			if (mids.length() > 0) {
				mids = mids.substring(0, mids.length() - 1);
			}
			UMenu = mdao.getUserMenuTree(session,mids).getTree();
		} catch (Exception e) {
			throw e;
		} finally {
			this.closeSession();
		}
		map.put("menulist", UMenu);
		return map;
	}
	
	/**
	 * 根据组织id查找用户
	 * @param orgId
	 * @return
	 * @throws Exception
	 */
	public List<PrmsUser> findUserByOrgId(String orgId) throws Exception{
		Session session = this.getSession();
		 List<PrmsUser> list = new ArrayList<PrmsUser>();
		try{
			list = dao.findUserByOrgId(session, orgId);
		}catch(Exception e){
			throw e;
		}finally {
			this.closeSession();
		}
		return list;
	}
	
	@Override
	public GenericHibernateDao getDao() {
		// TODO Auto-generated method stub
		return null;
	}
	
	
}
